import datetime
import os, time

from flask import Flask, render_template, url_for
from flask_socketio import SocketIO
import cv2
import json
import base64
import random

app = Flask(__name__)
app.config['SECRET_KEY'] = '78581099#lkjh'
socket_io = SocketIO(app)

face = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

cap = cv2.VideoCapture(0)


@app.route('/')
def index():
    return render_template('index.html')


@socket_io.on('takephoto')
def takephoto(data):
    if cap.isOpened():
        ret, img = cap.read()
    if ret:
        img = cv2.resize(img, (800, 600), fx=0.5, fy=0.5)  # 设置图片大小
        filename = gen_filename()
        cv2.imwrite(filename, img)
    return


def gen_filename():
    uuid_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
    tmp_file_name = '%s.jpeg' % uuid_str
    basepath = os.path.dirname(__file__)
    filename = os.path.join(basepath, 'static/imgs', tmp_file_name)
    return filename


@app.route('/images')
def image_list():
    img_urls = []
    names = os.listdir(os.path.join(app.static_folder, 'imgs'))
    for name in names:
        img_urls.append('static/' + os.path.join('imgs', name))
    return render_template('gallery.html', images=img_urls)

@app.route('/gallery')
def gallery():
    images = []
    names = os.listdir(os.path.join(app.static_folder, 'imgs'))
    for name in names:
        image = {}
        imgurl='static/' + os.path.join('imgs', name)
        image['src'] = imgurl
        image['width'] = 300
        image['type'] = 'jped'
        image['height'] = 200
        image['large_src'] = imgurl
        image['title'] = '&copy; Callum Trayner 2015'
        images.append(image)
    images = images + images
    return render_template('layout.html', images = images)


@socket_io.on('check')
def gen(json):
    while cap.isOpened():
        ret, img = cap.read()

        if ret:
            img = cv2.resize(img, (800, 600), fx=0.5, fy=0.5)  # 设置图片大小
            gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)  # 转换为灰度图片
            faces = face.detectMultiScale(gray, 1.1, 3, 0, (100, 100))
            for (x, y, w, h) in faces:  # 5个参数，一个参数图片 ，2 坐标原点，3 识别大小，4，颜色5，线宽
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

            eyes = eyeCascade.detectMultiScale(
                gray,
                scaleFactor=1.5,
                minNeighbors=10,
                minSize=(5, 5),
            )

            for (ex, ey, ew, eh) in eyes:
                cv2.rectangle(img, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

            frame = cv2.imencode('.jpg', img)[1].tobytes()
            frame = base64.encodebytes(frame).decode("utf-8")
            message(frame)
            socket_io.sleep(0)
        else:
            break


def message(msg, methods=['GET', 'POST']):
    print("Recieved message")
    socket_io.emit('image', msg)


if __name__ == "__main__":
    socket_io.run(app, debug=True, host='127.0.0.1', port=5000)
